<?php
// +----------------------------------------------------------------------
// | INPHP
// +----------------------------------------------------------------------
// | Copyright (c) 2021 https://inphp.cc All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( https://opensource.org/licenses/MIT )
// +----------------------------------------------------------------------
// | Author: lulanyin <me@lanyin.lu>
// +----------------------------------------------------------------------
namespace Inphp\Service\Http;

use Inphp\Service\Context;
use Inphp\Service\Object\Client;
use Inphp\Service\Router;
use Inphp\Service\Service;
use Swoole\ExitException;

class Server extends \Inphp\Service\Server
{
    /**
     * 服务类型
     * @var string
     */
    public string $server_type = Service::HTTP;

    public function __construct(bool $swoole = false)
    {
        //执行默认
        parent::__construct($swoole);
        if($swoole)
        {
            $this->server->on("request", [$this, "onRequest"]);
        }

    }
    
    /**
     * 接收到http请求
     * @param \Swoole\Http\Request|null $request
     * @param \Swoole\Http\Response|null $response
     */
    public function onRequest(\Swoole\Http\Request|null $request = null, \Swoole\Http\Response|null $response = null) : void
    {
        if($this->server){
            //swoole
            //主域名
            $host = $request->header['host'];
            $ip = $swoole_request->header['x-real-ip'] ?? ($request->server['remote_addr'] ?? null);
            //请求方式
            $method = $request->server['request_method'];
            //路径信息
            $path = $request->server['path_info'] ?? '';
            $uri = $request->server['request_uri'] ?? '';
            $path = !empty($path) ? $path : $uri;
            $http_x_requested_with = $request->header['x-requested-with'] ?? null;
            //交给路由处理，由HTTP控制器处理数据返回，得到数据
            $client = new Client([
                "https"     => ($request->header['X-Request-Scheme'] ?? null) == 'https',
                "host"      => $host,
                "ip"        => $ip,
                "server"    => $request->server,
                "method"    => $method,
                "ajax"      => $http_x_requested_with == 'XMLHttpRequest',
                //"session"   => Session::get(), 由于未初始化，不可使用 Session
                "cookie"    => $request->cookie,
                "get"       => $request->get,
                "post"      => $request->post,
                "files"     => $request->files,
                "raw_post_data" => $request->rawContent(),
                "uri"       => $path,
                "origin"    => $request->header['origin'] ?? '',
                "id"        => $request->fd
            ]);
            //将swoole\http\request 保存到上下文
            //Context::setRequest($request);
        }else{
            //php-fpm/fast-cgi
            //session 开启
            if(session_status() !== PHP_SESSION_ACTIVE){
                @session_start();
            }
            $host = $_SERVER['HTTP_HOST'];
            $ip = $_SERVER['REMOTE_ADDR'];
            $method = $_SERVER['REQUEST_METHOD'];
            $path = $_SERVER['PATH_INFO'] ?? "";
            $uri = $_SERVER['REQUEST_URI'] ?? "";
            $path = !empty($path) ? $path : $uri;
            $http_x_requested_with = $_SERVER['HTTP_X_REQUESTED_WITH'] ?? null;
            //保存客户端数据
            $client = new Client([
                "https"     => $_SERVER['REQUEST_SCHEME'] == "https",
                "host"      => $host,
                "ip"        => $ip,
                "server"    => $_SERVER,
                "method"    => $method,
                "session"   => $_SESSION,
                "cookie"    => $_COOKIE,
                "get"       => $_GET,
                "post"      => $_POST,
                "files"     => $_FILES,
                "raw_post_data" => file_get_contents("php://input") ?? null,
                "uri"       => $path,
                "ajax"      => $http_x_requested_with == 'XMLHttpRequest',
                "id"        => 0,
                "origin"    => ""
            ]);
        }
        //保存客户端数据到上下文
        Context::setClient($client);
        //客户端就绪后，保存session
        Context::getClient()->set('session', Session::get());
        //使用统一对象
        $_response = new Response($response);
        //保存到上下文
        Context::setResponse($_response);
        try{
            //中间键
            $this->processMiddlewares("on_request", [$request, $_response]);
            //路由处理
            $status = Router::process($client->uri, $client->method, $this->server_type);
            //得到状态数据，响应数据
            $_response->start($status)->send();
        }catch (ExitException $exception){
            //捕获exit() 让 swoole 服务持续运行
            $this->processMiddlewares("on_request_exception", [$exception, $request, $_response]);
        }
    }

    /**
     * 启动服务
     */
    public function start(){
        //启动前
        $this->beforeStart();
        //区分处理
        if($this->server){
            //启动 swoole http 服务
            $this->server->start();
        }else{
            //php-fpm / fast-cgi
            $this->onRequest();
        }
    }

    
}